<template>
  <el-dialog title="角色权限" :visible="visible" @close="handleDialogClose" width="600px">
    <el-tree
      :data="permissionList"
      show-checkbox
      check-strictly
      highlight-current
      default-expand-all
      node-key="permissionId"
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
      ref="tree"
    ></el-tree>
    <div slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import RoleService from '../../../../service/role'
import PermissionService from '../../../../service/permission'

export default {
  props: {
    show: {
      type: Boolean,
      required: true,
      default: () => false
    },
    data: {
      type: Object,
      required: false,
      default: () => {}
    }
  },
  data() {
    return {
      visible: false,
      permissionList: [],
      defaultCheckedKeys: [],
      defaultProps: {
        label: 'permissionName',
        children: 'children'
      }
    }
  },
  methods: {
    // 处理Dialog关闭事件
    handleDialogClose() {
      this.$emit('update:show')
    },
    // 获取权限列表
    getPermissions() {
      PermissionService.getPermissionsByKeyword().then(res => {
        this.permissionList = res.data.list
      })
    },
    // 提交表单
    submitForm() {
      const permissionIds = this.$refs.tree.getCheckedKeys()
      RoleService.insertRolePermission(this.data.roleId, permissionIds).then(
        res => {
          // 提示
          this.$message.success(res.message)
          // 关闭Dialog
          this.visible = false
          // 派发事件刷新Table
          this.$emit('success', 1)
        }
      )
    }
  },
  watch: {
    show(value) {
      this.visible = value
    },
    data(value) {
      if (!value) {
        return
      }
      let permissionIds = []
      value.permissions.forEach(item => permissionIds.push(item.permissionId))
      this.defaultCheckedKeys = permissionIds
    }
  },
  mounted() {
    this.getPermissions()
  }
}
</script>

<style lang="stylus" scoped></style>
